'''
@author: harumonia
@site:
@datetime: 2020/3/14 20:37
@software: PyCharm
'''
from flask_admin.contrib.sqla import ModelView
from flask_login import current_user
from wtforms import TextAreaField
from wtforms.widgets import TextArea

from application.extensions import db
from application.models.base import Basedb
from .outline import Outline

from ..utils.time_handler import get_now_datetime


class Article(Basedb):
    __tablename__ = 'article'
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='id')
    title = db.Column(db.String(100), nullable=False, comment='title of article')
    status = db.Column(db.Boolean)
    keyword = db.Column(db.String(100))
    content = db.Column(db.TEXT, comment='content of article')
    create_date = db.Column(db.DateTime, comment='create_date of article')
    edit_date = db.Column(db.DateTime, comment='edit_date of article')
    outline_id = db.Column(db.BigInteger, db.ForeignKey('outline.id'))
    rank = db.Column(db.Integer)
    outline = db.relationship('Outline',
                              backref=db.backref('article'))

    def to_dict(self):
        res = {}
        for foo in dir(self):
            if not foo.startswith('_') and isinstance(getattr(self, foo), (int, str)) and foo not in ['outline_id',
                                                                                                      'status']:
                res[foo] = getattr(self, foo)
        auth_info = Outline.query.filter_by(id=self.outline_id).first()
        res['content'] = res.pop('content')
        res['outline'] = auth_info.name
        return res

    def tt(self):
        return self.rank + '|' + self.title


class CKEditor(TextArea):
    def __call__(self, field, **kwargs):
        c = kwargs.pop('class', '') or kwargs.pop('class_', '')
        kwargs['class'] = u'%s %s' % ('ckeditor', c)
        # field.name = 'ckeditor'
        # field.id = 'ckeditor'
        return super(CKEditor, self).__call__(field, **kwargs)


class CKEditorField(TextAreaField):
    widget = CKEditor()


class ArticleView(ModelView):
    form_overrides = dict(content=CKEditorField)
    create_template = 'edit_article.html'
    edit_template = 'edit_article.html'

    column_exclude_list = ['content', 'file_path', 'edit_date', 'intro', 'status']
    column_filters = ['create_date', 'outline_id']

    form_excluded_columns = ('create_date', 'edit_date', 'status')

    can_view_details = False

    def on_model_change(self, form, Article, is_created):
        Article.outline_id = current_user.id
        Article.edit_date = get_now_datetime()
        if is_created:
            Article.create_date = get_now_datetime()
            Article.status = True

    def on_model_delete(self, Article):
        Article.status = False
